package com.yy.studyspringboot.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {
    /**  Semaphore---同步器
            用来限流，接口最多同时只能线程调用，其余的等待
     */

    public static void main(String[] args) throws InterruptedException {
        //举例每次最多检票2人
        ExecutorService service = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < 8; i++) {
            final int num = i;
            Runnable runnable = () -> {
                try {
                    semaphore.acquire();
                    System.out.println("no " + num + " check");
                    TimeUnit.SECONDS.sleep((long) Math.random() * 200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                    System.out.println("---- " + "no " + num + " finish");
                }
            };
            service.execute(runnable);
        }
    }


}
